/**************************************************************************
 *
 * Copyright (c) 2015-2017  QIKU Company             　　　　　　　            
 *                 奇酷软件（深圳）有限公司  版权所有 2015-2017
 *
 * PROPRIETARY RIGHTS of QIKU Company are involved in the  　　　　　　     
 * subject matter of this material.  All manufacturing, reproduction, use, 
 * and sales rights pertaining to this subject matter are governed by the  
 * license agreement.  The recipient of this software implicitly accepts   
 * the terms of the license.                                               
 * 本软件文档资料是奇酷公司的资产,任何人士阅读和使用本资料必须获得                     
 * 相应的书面授权,承担保密责任和接受相应的法律约束.                                 
 *
 **************************************************************************/
package com.yw.android.common.http;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.yw.android.common.utils.LOG;
import com.yw.android.common.utils.SystemUtils;
import com.yw.android.common.utils.TextUtils;

import java.util.Locale;

/**
 * 网络接入点管理，重点需要处理WAP接入点的情况
 *
 * @author yuanwei
 */
public class ProxyManager {

    /**
     * APN查询URI
     */
    private static Uri preferredAPNUrl = null;

    /**
     * 静态加载
     */
    static {
        preferredAPNUrl = Uri.parse("content://telephony/carriers/preferapn");
    }

    /**
     * 应用上下文对象
     */
    private Context context = null;

    /**
     * 构造函数
     *
     * @param context 上下文对象
     */
    private ProxyManager(Context context) {
        this.context = context;
    }

    /**
     * 获取ProxyManager对象
     *
     * @param context 上下文对象
     * @return ProxyManager对象
     */
    public static ProxyManager getDefault(Context context) {
        return new ProxyManager(context.getApplicationContext());
    }

    /**
     * 获取代理信息，如果为空，表明没有使用代理
     *
     * @return 代理信息
     */
    public ApnNode getNode() {
        try {
            String networkType = SystemUtils.getNetworkType(context);

            if (!TextUtils.empty(networkType)) {
                if (networkType.toLowerCase(Locale.getDefault()).contains("wap")) {
                    return getApnNodeInternal();
                }
            }
        } catch (Exception e) {
            LOG.e("get proxy node failed(Exception): " + e.getMessage());
        }

        return null;
    }

    /**
     * 移动网络为WAP代理下，获取接入点信息
     *
     * @return 接入点信息
     */
    private ApnNode getApnNodeInternal() {
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = null;
        ApnNode entry = null;

        try {
            cursor = resolver.query(preferredAPNUrl,
                    new String[]{
                            "apn", "proxy", "port"
                    },
                    null, null, null);

            if ((null != cursor) && cursor.moveToFirst()) {
                do {
                    String apn = cursor.getString(cursor.getColumnIndex("apn"));
                    String proxy = cursor.getString(cursor.getColumnIndex("proxy"));
                    String port = cursor.getString(cursor.getColumnIndex("port"));

                    if (!TextUtils.empty(apn)) {
                        // 如果代理地址为空，那么获取默认保存的代理地址
                        if (TextUtils.empty(proxy)) {
                            proxy = getDefaultApnNode(apn);
                        }

                        if (!TextUtils.empty(proxy)) {
                            entry = new ApnNode();
                            entry.setApn(apn);
                            entry.setProxy(proxy);

                            try {
                                if (TextUtils.empty(port)) {
                                    entry.setPort(80);
                                } else {
                                    entry.setPort(Integer.parseInt(port));
                                }
                            } catch (NumberFormatException e) {
                                entry.setPort(80);
                            } catch (Exception e) {
                                entry.setPort(80);
                            }
                        }

                        break;
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            LOG.e("get apn entry failed(Exception)", e);
        } finally {
            if (null != cursor) {
                cursor.close();
                cursor = null;
            }
        }

        return entry;
    }

    /**
     * 获取默认代理主机地址
     *
     * @param apn 指定APN名称
     * @return 代理服务器地址
     */
    private String getDefaultApnNode(String apn) {
        if (!TextUtils.empty(apn)) {
            String apnl = apn.toLowerCase(Locale.getDefault());

            if (apnl.contains("cmwap")
                    || apnl.contains("uniwap")
                    || apnl.contains("3gwap")) {
                return "10.0.0.172";
            } else if (apnl.contains("ctwap")) {
                return "10.0.0.200";
            }
        }

        return null;
    }

    /**
     * 代理对象
     *
     * @author yuanwei
     */
    public static class ApnNode {
        /**
         * 接入点名称
         */
        private String apn = null;

        /**
         * 代理地址
         */
        private String proxy = null;

        /**
         * 代理端口
         */
        private int port = 0;

        /**
         * 获取接入点名称
         *
         * @return 接入点名称
         */
        public String getApn() {
            return apn;
        }

        /**
         * 设置接入点名称
         *
         * @param apn 接入点名称
         */
        public void setApn(String apn) {
            this.apn = apn;
        }

        /**
         * 获取代理地址
         *
         * @return 代理地址
         */
        public String getProxy() {
            return proxy;
        }

        /**
         * 设置代理地址
         *
         * @param proxy 代理地址
         */
        public void setProxy(String proxy) {
            this.proxy = proxy;
        }

        /**
         * 获取代理端口
         *
         * @return 代理端口
         */
        public int getPort() {
            return port;
        }

        /**
         * 设置代理端口
         *
         * @param port 代理端口
         */
        public void setPort(int port) {
            this.port = port;
        }

        @Override
        public String toString() {
            return (apn + " " + proxy + ":" + port);
        }
    }
}
